﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Adams.Web.Areas.MyAdams.Logic.Profile
{
    public static class Password
    {
        public static MyAdams.Models.Profile.Password.PageLoad PageLoad(int memberid)
        {
            return new MyAdams.Models.Profile.Password.PageLoad();
        }

        public static Adams.Web.Models.FormOutput SavePassword(int memberid, Adams.Web.Areas.MyAdams.Models.Profile.Password.FormInput input)
        {
            var output = Adams.Web.Logic.Validation.PerformBasicValidation(input);

            if (output.IsValid)
            {
                if (!Shared.Str.IsEqual(input.Password1, input.Password2))
                {
                    output.InvalidFields.Add(new Adams.Web.Models.InvalidField() { Name = "Password2", Code = 6 });
                }

                if (output.IsValid)
                {
                    var memberinfo = MyAdams.Data.Profile.Password.GetMemberInfo(memberid);
                    string hashedPassword = Adams.Shared.Encryption.HashPassword(input.Password, memberinfo.PasswordSalt);
                    if (!Shared.Str.IsEqual(hashedPassword, memberinfo.PasswordHash))
                    {
                        output.InvalidFields.Add(new Adams.Web.Models.InvalidField() { Name = "Password", Code = 5 });
                    }

                    if (output.IsValid)
                    {
                        hashedPassword = Adams.Shared.Encryption.HashPassword(input.Password1, memberinfo.PasswordSalt);
                        MyAdams.Data.Profile.Password.SavePassword(memberid, hashedPassword);
                        output.IsSaved = true;
                    }
                }
            }

            return output;
        }
    }
}